#ifndef HTTPSERVER_H
#define HTTPSERVER_H


#include <QTcpServer>
#include <QTcpSocket>
#include <QCoreApplication>

// class HttpServer : public QTcpServer {
//     Q_OBJECT
// public:
//     HttpServer(QObject *parent = nullptr) : QTcpServer(parent) {
//         connect(this, &QTcpServer::newConnection, this, &HttpServer::handleNewConnection);
//     }

// private slots:
//     void handleNewConnection() {
//         QTcpSocket *clientSocket = nextPendingConnection();
//         connect(clientSocket, &QTcpSocket::readyRead, [clientSocket]() {
//             QByteArray requestData = clientSocket->readAll();

//             // 简单的 HTTP 响应
//             QByteArray response =
//                 "HTTP/1.1 200 OK\r\n"
//                 "Content-Type: text/plain\r\n"
//                 "Content-Length: 13\r\n"
//                 "\r\n"
//                 "Hello, World!";

//             clientSocket->write(response);
//             clientSocket->flush();
//             clientSocket->disconnectFromHost();
//         });
//     }
// };

class HttpServer : public QTcpServer {
    Q_OBJECT

public:
    explicit HttpServer(QObject *parent = nullptr) : QTcpServer(parent) {
        connect(this, &HttpServer::newConnection, this, &HttpServer::handleNewConnection);
    }

private slots:
    void handleNewConnection() {
        QTcpSocket *clientSocket = nextPendingConnection();
        connect(clientSocket, &QTcpSocket::readyRead, this, [this, clientSocket]() {
            QByteArray requestData = clientSocket->readAll();
            qDebug() << "Received request:" << requestData;

            // 解析请求（简单处理）
            QString response;
            if (requestData.startsWith("POST")) {
                response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nData received";
            } else {
                response = "HTTP/1.1 405 Method Not Allowed\r\nContent-Type: text/plain\r\n\r\nOnly POST requests are allowed";
            }

            // 发送响应
            clientSocket->write(response.toUtf8());
            clientSocket->flush();
            clientSocket->disconnectFromHost();
        });

        connect(clientSocket, &QTcpSocket::disconnected, clientSocket, &QTcpSocket::deleteLater);
    }
};



#endif // HTTPSERVER_H
